<?php

namespace App\Kuafu\Mqtt\Command;

use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Mqtt\Enum\MqttCodeEnum;
use App\Kuafu\Nsq\Enum\NsqCodeEnum;
use App\Kuafu\User\Model\User;
use App\Library\FeiShu\SendFs;
use App\Support\MQTT;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Kuafu\GeneralFs\BuildFs;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubMqttSendCommand extends Command
{
    protected $signature = 'mqtt:nsq-sub-mqtt-send';

    protected $description = 'NSQ订阅mqtt发送';

    public function handle()
    {
        ini_set('memory_limit', '2G');

        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqCodeEnum::MQTT_SEND, NsqCodeEnum::MQTT_SEND_RMS_CHANNEL,
                function (Message $message) {
                    $data = $message->data();

                    // 参数校验
                    if (!$this->valid($data)) {
                        $message->done();
                        return;
                    }

                    // 执行
                    $this->process($data);

                    $message->done();
                }
            );
    }

    private function valid(array $data): bool
    {
        $validator = Validator::make($data, [
            'shopId'      => 'required|integer',
            'cmd'         => 'required|string',
            'params'      => 'required|array',
            'connectType' => ['required', 'integer', Rule::in(array_keys(MQTT::MQTT_CONNECT_TYPE_TEXT))],
        ]);

        if ($validator->fails()) {
            Log::warning("NsqSubMqttSendCommand valid error:" . $validator->errors()->first(), $data);
            return false;
        }

        return true;
    }

    private function process(array $data): void
    {
        MQTT::send($data['shopId'], $data['cmd'], $data['params'], $data['connectType']);
    }
}
